#coding:utf-8
import http.client
import json
import sys
import requests
import codecs
import pymysql
import time
from urllib.request import urlopen
import sys

Host = "139.224.35.125"
Url = "http://www.live-ctrl.com/aijukex/op/op_queryPowerWarn"
Url1 = "http://www.live-ctrl.com/aijukex/op/op_powerWarnDatas"
port = 80
def httpSend(host, url, port, data_str):
    conn = http.client.HTTPConnection(host, port, timeout = 5)
    data = {'data':data_str}
    headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "*/*"}
    params = urllib.parse.urlencode(data)
    conn.request("POST", url, params, headers)
    response = conn.getresponse()
    data = response.read()
    conn.close()
    return data
def list_to_json(listData):
	list_json = []
	#for elem in listData:
	list_json.append((listData))
	dataJson = json.dumps(list_json,ensure_ascii=False)
	return dataJson

def httpGet(q):
    conn = http.client.HTTPConnection("139.224.35.125",80,timeout = 1)
    conn.request(method="GET", url="http://www.live-ctrl.com/aijukex/op/op_queryPowerWarn")
    response = conn.getresponse()
    response = urlopen("http://www.live-ctrl.com/aijukex/op/op_queryPowerWarn").read().decode('utf8')
    obj = json.loads(response)
    #print(obj,type(obj))
    for elem in obj:
        #print(elem)
        elem['id']=str(elem['id'])
        #nnn = obj[0]['name']
        www = '1234'
        conn = pymysql.connect("localhost", "root", "1234", "moyan", charset="utf8")
        #print("查询数据库》》》连接成功")
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM historydata  WHERE name LIKE %s and id_id = %s ORDER BY id DESC LIMIT 1 " , (elem['name'] , www) )
        data = cursor.fetchall()
        if data:
            print("查询到%s数据"%elem['name'])
            if int(data[0][3]) > int(elem['warnPower']):
                dic = {}
                for elem in data:
                    # print(elem)
                    dic['id'] = elem[1]
                    dic['name'] = elem[2]
                    dic['power'] = elem[3]
                    dic['state'] = elem[4]
                dataJson = list_to_json(dic)
                try:
                    htttpSend("139.224.35.125", "http://www.live-ctrl.com/aijukex/op/op_powerWarnDatas", 80, dataJson)
                    print("报警数据上报成功")
                except:
                    print("报警数据上报失败")
            else:
                print("目前没有%s报警数据"%(elem['name']))
    conn.close()
    time.sleep(60)




def main():
    httpGet(Host,Url,port)
  




if __name__ == '__main__':
    main()